function bvqx_dtsf_writefibers(fid, fibers)
% bvqx_dtsf_writefibers  - write fibers to DTSF file
%
% FORMAT:       writeok = bvqx_dtsf_writefibers(fid, fibers)
%
% Input fields:
%
%       fid         output file fid (already open)
%       fibers      Nx1 struct array with fields
%        .NrOfPoints   number of points for that fiber
%        .Selected     uint8, either 0 or 1
%        .RGB          1x3 uint8 array
%        .FromToPoint  1x2 double array, [0, NrOfPoints]
%        .Coord        Px3 coordinates of fiber points
%
% Output fields
%
%       fibers      Nx1 struct array with fields
%
% See also BVQXfile, bffio

% Version:  v0.8a
% Build:    9102221
% Date:     Oct-22 2009, 3:53 PM CEST
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 2 || ...
   ~isa(fid, 'double') || ...
    isempty(fid) || ...
   ~isreal(fid) || ...
   ~any(fopen('all') == fid(1)) || ...
   ~isstruct(fibers) || ...
   ~isfield(fibers, 'NrOfPoints') || ...
   ~isfield(fibers, 'Selected') || ...
   ~isfield(fibers, 'RGB') || ...
   ~isfield(fibers, 'FromToPoint') || ...
   ~isfield(fibers, 'Coord')
    error( ...
        'BVQXtools:BadArgument', ...
        'Bad or missing argument.' ...
    );
end

% try ...
numfib = numel(fibers);
try

    % loop over fibers
    for fc = 1:numfib

        % write fiber data
        fwrite(fid, fibers(fc).NrOfPoints(1)   , 'uint32');
        fwrite(fid, fibers(fc).Selected(1)     , 'uint8');
        fwrite(fid, fibers(fc).RGB(1:3)        , 'uint8');
        fwrite(fid, fibers(fc).FromToPoint(1:2), 'uint32');
        fwrite(fid, fibers(fc).Coord(1:fibers(fc).NrOfPoints(1), 1:3)', 'single');
    end

catch
    rethrow(lasterror);
end
